/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.h5;

import cn.easyplatform.dao.BizDao;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.h5.OrgVo;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.type.IResponseMessage;

import java.util.ArrayList;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class GetOrgCmd extends AbstractCommand<SimpleRequestMessage> {

	/**
	 * @param req
	 */
	public GetOrgCmd(SimpleRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		try {
			BizDao dao = cc.getBizDao();
			List<FieldDo> params = new ArrayList<FieldDo>(1);
			String sql = null;
			if (req.getBody() == null || "*".equals(req.getBody())) {
				params.add(new FieldDo(FieldType.VARCHAR, cc.getUser().getOrg()
						.getId()));
				sql = "SELECT orgId, name FROM sys_org_info WHERE orgId <> ? ORDER BY orgId";
			} else {
				String[] orgs = (String[]) req.getBody();
				StringBuilder sb = new StringBuilder(
						"SELECT orgId, name FROM sys_org_info WHERE orgId IN(");
				for (int i = 0; i < orgs.length; i++) {
					if (!orgs[i].equals(cc.getUser().getOrg().getId())) {
						sb.append("?");
						if (i < (orgs.length - 1))
							sb.append(",");
						params.add(new FieldDo(FieldType.VARCHAR, orgs[i]));
					}
				}
				if (sb.charAt(sb.length() - 1) == ',')
					sb.deleteCharAt(sb.length() - 1);
				sb.append(")").append(" ORDER BY orgId");
				sql = sb.toString();
				sb = null;
			}
			List<FieldDo[]> result = dao.selectList(sql, params);
			List<OrgVo> groups = new ArrayList<OrgVo>();
			for (FieldDo[] fields : result) {
				String orgId = fields[0].getValue().toString();
				String name = fields[1].getValue().toString();
				OrgVo gv = new OrgVo(orgId, name);
				groups.add(gv);
			}
			return new SimpleResponseMessage(groups);
		} catch (Exception ex) {
			return new SimpleResponseMessage();
		}
	}
}
